package com.ykdl.member.kid.messagebox;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ISaveUserInfoForAutoLoginSuccess;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ykdl.member.kid.R;
import com.ykdl.member.base.QLog;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.adapters.MyChatMsgViewAdapter;
import com.ykdl.member.kid.beans.ImageBean;
import com.ykdl.member.kid.beans.PmListBean;
import com.ykdl.member.kid.beans.ResultBean;
import com.ykdl.member.kid.beans.UserActorBean;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.image.ImageLoader;
import com.ykdl.member.kid.models.FileMetas;
import com.ykdl.member.kid.util.CameraHelp;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.views.ResizeLayout;
import com.ykdl.member.views.SelectToolDataView;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class ChatLetterActivity extends BaseScreen implements OnClickListener{
	private RefreshListView chat_list ;
	private MyChatMsgViewAdapter chatadapter ;
	private SelectToolDataView selToolData ;
	private ImageView photo1  ;
	private LinearLayout seltool_imgs ;
	private RelativeLayout seltool_imgs_div_1;
	private ArrayList<SoftReference<Bitmap>> mBitmapRefs = new ArrayList<SoftReference<Bitmap>>();  
	private ArrayList<ImageBean> photopath = new ArrayList<ImageBean>();
	private int  photo_fieid = -1;
	private String actor_dialogue_id ;
	private String dialogue_id ;
	private String TAG = "ChatLetterActivity";
	private EditText topic_answer_input ;
	private Button topic_answer_send ;
	private Button main_left ;
	private boolean is_blocked = false;
	private UserActorBean target_actor ;
	private boolean is_clear_edite= true;
	private TextView main_title ;
	private Dialog dialog ;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chatletteractivity_xml);
		actor_dialogue_id = this.getIntent().getStringExtra(KidAction.ACTOR_DIALOGUE_ID);
		dialogue_id = this.getIntent().getStringExtra(KidAction.DIALOGUE_ID);
		inint();
		}
	public void inint() {
		main_title = (TextView)findViewById(R.id.main_title);
		topic_answer_input = (EditText)findViewById(R.id.topic_answer_input);
		hideKeyBorad(topic_answer_input);
		findViewById(R.id.main_right).setOnClickListener(this);
		topic_answer_input.setOnClickListener(this);
		topic_answer_send = (Button)findViewById(R.id.topic_answer_send);
		main_left = (Button)findViewById(R.id.main_left);
		main_left.setOnClickListener(this);
		topic_answer_send.setOnClickListener(this);
		chatadapter = new MyChatMsgViewAdapter(this,TAG);
		chat_list = (RefreshListView)findViewById(R.id.chat_list);
		chat_list.setMoreButtoIsGon("点击后加载最新");
		selToolData = (SelectToolDataView)findViewById(R.id.share_data_panle);
		
		selToolData.setOwerActivity(this);
		selToolData.setCheckBoxGon();
		selToolData.setMax_photos(1);
		photo1 = (ImageView)findViewById(R.id.photo1);
		findViewById(R.id.close1).setOnClickListener(this);
		seltool_imgs_div_1 = (RelativeLayout)findViewById(R.id.seltool_imgs_div_1);
		seltool_imgs = (LinearLayout)findViewById(R.id.seltool_imgs);
		ResizeLayout root=(ResizeLayout)findViewById(R.id.iask_main_root);
		root.setOnResizeListener(new ResizeLayout.OnResizeListener() {

			public void OnResize(int w, int h, int oldw, int oldh) {
				// int change = ResizeLayout.BIGGER;
				if (h < oldh) {
					// change = ResizeLayout.SMALLER;
				} else if (h - oldh > 200) {
					// 键盘的高度应该会大于这个值， 删除一个汉字，也会小于这个值，所以变化在200之外才是键盘隐藏，
					// 否则是用键盘在删除文字，不用处理
					if (is_clear_edite) {
						topic_answer_input.setText("");
						selToolData.setVisibility(View.GONE);
						topic_answer_send.setBackgroundResource(R.drawable.topic_send_bg_white);
					}
				}
			}
		});
		chat_list.setMoreClick(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				getChatLetter();
			}
		});
		selToolData.setEditText(topic_answer_input,seltool_imgs);
		getChatLetter();
	}
	public void getChatLetter() {
		showProgress("正加载请稍等...");
		String  pageurl =KidConfig.PM_INBOX_INFO;
		Map<String,String> map = new HashMap<String, String>();
		map.put("start_id", "0");
		map.put("cursor", "0");
		map.put("count", "50");
		map.put("mark_read", "1");
		HttpBaseRequest request  =  Wxxr.getInstance().getRequest(pageurl+actor_dialogue_id, map,"");
		 TaskManager.startHttpRequest(request, new getChatLetterTag(),  PmListBean.class);
	}
	
	class getChatLetterTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			
			if (t instanceof PmListBean) {
				PmListBean bean = (PmListBean)t;
				if (bean.getError()==null) {
					chatadapter.setList(bean.getList());
					chatadapter.setActorid(bean.getCurrent_actor_id());
					chat_list.setAdapter(chatadapter);
					target_actor = bean.getTarget_actor();
					main_title.setText(target_actor.getDisplay_name());
					if (bean.isIs_blocked()) {
						is_blocked = true ;
						main_left.setText("已屏蔽");
					}else {
						is_blocked = false ;
						main_left.setText("屏蔽私信");
					}
					chatadapter.notifyDataSetChanged();
					chat_list.setSelection(chat_list.getCount() - 1);
				}else {
					Toast.makeText(mContext, "加载失败", 1).show();
				}
				chat_list.onRefreshComplete();
				chat_list.setFecthMoreOk();
				
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "加载失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	public void sedChatLetter(boolean issendimag) {
		if (issendimag) {
			showProgress("正在发送请稍等...");
			String  pageurl =KidConfig.PM_INBOX_INFO;
			HttpParameters bodyParams = new HttpParameters();
			String message = null ;
			try {
				message = URLEncoder.encode(topic_answer_input.getText().toString(), "utf8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			bodyParams.put("content", "");
			if (photo_fieid!=-1) {
				bodyParams.put("file_ids", photo_fieid+"");
			}
			bodyParams.put("attachment_type", "1");
			HttpBaseRequest request  =  Wxxr.getInstance().postBaseRequest(pageurl+dialogue_id+"/messages", bodyParams,"");
			 TaskManager.startHttpRequest(request, new sedChatLetterTag(),  ResultBean.class);
		}else {
			if (topic_answer_input.getText().toString().trim().length()>0) {
				showProgress("正在发送请稍等...");
				String  pageurl =KidConfig.PM_INBOX_INFO;
				HttpParameters bodyParams = new HttpParameters();
				String message = null ;
				try {
					message = URLEncoder.encode(topic_answer_input.getText().toString(), "utf8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				bodyParams.put("content", message);
				bodyParams.put("attachment_type", "1");
				HttpBaseRequest request  =  Wxxr.getInstance().postBaseRequest(pageurl+dialogue_id+"/messages", bodyParams,"");
				 TaskManager.startHttpRequest(request, new sedChatLetterTag(),  ResultBean.class);
			}else {
				Toast.makeText(mContext, "请填写话题内容", 1).show();
			}
		}
		
		
	}
	
	class sedChatLetterTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof ResultBean) {
				ResultBean bean = (ResultBean)t;
				if (bean.getError()==null) {
					Toast.makeText(mContext, "发送成功", 1).show();
					hideKeyBorad(topic_answer_input);
					topic_answer_input.setText("");
					photopath.clear();
					seltool_imgs.setVisibility(View.GONE);
					getChatLetter();
				}else {
					Toast.makeText(mContext, "发送失败", 1).show();
				}
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "发送失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	protected void onResume() {
		// TODO Auto-generated method stub
		ImageLoader.getInstance().setCurrentActivity(TAG);
		super.onResume();
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		ImageLoader.getInstance().pause(TAG);
		super.onPause();
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.close1:
			seltool_imgs_div_1.setVisibility(View.GONE);
			photopath.remove(0);
			setImage();
			break;
		case R.id.topic_answer_send:
			sedChatLetter(false);
			break;
			case R.id.topic_answer_input:
				showKeyBorad(topic_answer_input);
				selToolData.setVisibility(View.VISIBLE);
				break;
			case R.id.main_right:
				this.finish();
				break;
			case R.id.main_left:
				showfinddilog(is_blocked);
				break;
			case R.id.OK:
				addOrDletBlackList(is_blocked);
				break;
			case R.id.cance:
				dialog.dismiss();
				break;
		default:
			break;
		}
	}
	public void addOrDletBlackList(boolean isDelte) {
		String  pageurl =KidConfig.ADD_BLACKLIST;
		HttpParameters bodyParams = new HttpParameters();
		bodyParams.put("actor_id", target_actor.getActor_id()+"");
		HttpBaseRequest request;
		if (isDelte) {
			 request  =  Wxxr.getInstance().deltteRequest(pageurl, bodyParams);
		}else {
			 request  =  Wxxr.getInstance().postBaseRequest(pageurl, bodyParams,"");
		}
		
		 TaskManager.startHttpRequest(request, new addBlackListTag(isDelte),  ResultBean.class);
	}
	class addBlackListTag implements ITag {
		private boolean isDelte;
		public addBlackListTag(boolean isDelte){
			this.isDelte = isDelte ;
		}
		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof ResultBean) {
				ResultBean bean = (ResultBean)t;
				if (bean.getError()==null) {
					if(isDelte){
						main_left.setText("屏蔽消息");
						Toast.makeText(mContext, "取消屏蔽成功", 1).show();
						is_blocked = false ;
					}else {
						is_blocked = true ;
						main_left.setText("已屏蔽");
						Toast.makeText(mContext, "屏蔽成功", 1).show();
					}
					
				}else {
					Toast.makeText(mContext, "失败"+bean.getDesc(), 1).show();
				}
				dialog.dismiss();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == -1) {
			String path = null;
			try {
				path = selToolData.setPicture(requestCode, resultCode, data);
				// 第一次是拍照或者选择照片 回来，第二次才是 裁剪完成
				is_clear_edite = false ;
				Log.e("alan", "------------------path:"+path);
				ImageBean bean = new ImageBean();
				bean.setPath(path);
				File file = new File(path);
				putphoto(file,true);
				if (requestCode == CameraHelp.SURVEY_PHOTO_ZOOM) {
				//裁剪完成的.
				}
			} catch (Throwable ee) {
				QLog.debug(TAG, "内存不足===!!!!!!1");
				Toast.makeText(this, "内存不足", Toast.LENGTH_SHORT).show();
				// System.gc();
				path = null;
			}
			if (path != null) {
			}
		}
	}
	public void setImage() {
		int size = photopath.size();
		if (size==1) {
			seltool_imgs.setVisibility(View.VISIBLE);
			seltool_imgs_div_1.setVisibility(View.VISIBLE);
			Bitmap bitmap1 = BitmapFactory.decodeFile(photopath.get(0).getPath());
			mBitmapRefs.add(new SoftReference<Bitmap>(bitmap1));
			photo1.setImageBitmap(bitmap1);
		}else {
			seltool_imgs.setVisibility(View.GONE);
			seltool_imgs_div_1.setVisibility(View.GONE);
		}
		
	}
	public void putphoto(File file,boolean issendimag) {
		showProgress("正在发送请稍等...");
		String  pageurl = KidConfig.UPLOAD_PHOTO;
		HttpBaseRequest request  =  Wxxr.getInstance().uploadFile(pageurl,file);
		 TaskManager.startHttpRequest(request, new putphotoTag(issendimag),  FileMetas.class);
	}
	class putphotoTag implements ITag {
		private boolean issendimag ;
		public putphotoTag(boolean issendimag){
			this.issendimag = issendimag ;
		}
		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof FileMetas) {
				FileMetas bean = (FileMetas)t;
				Log.e("alan", "---------------getDownload_url---path:"+bean.getDownload_urls().getOrigin().getUrl());
				photo_fieid=bean.getFile_id();
				sedChatLetter(issendimag);
				
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "图片上传失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	public void showfinddilog(boolean is_blocked) {
		dialog = new Dialog(this, R.style.bubble_dialog);
		dialog.setCanceledOnTouchOutside(true);
		Window dialogWindow = dialog.getWindow();
		WindowManager manager = this.getWindowManager();
		LayoutParams params = dialogWindow.getAttributes();// 获取LayoutParams
		dialogWindow.setGravity(Gravity.BOTTOM);
		params.width = manager.getDefaultDisplay().getWidth();
		dialogWindow.setAttributes(params);
		dialog.setContentView(R.layout.no_chat_dialog_xml);
		Button mTitle = (Button)dialog.findViewById(R.id.OK);
		if (is_blocked) {
			mTitle.setText("取消屏蔽私信");
		}else {
			mTitle.setText("屏蔽私信");
		}
		dialog.findViewById(R.id.OK).setOnClickListener(this);
		dialog.findViewById(R.id.cance).setOnClickListener(this);
		dialog.show();
	}
}
